const request = require('../../utils/request')

Page({
  data: {
    // 科室列表（固定列表）
    departmentList: [
      { id: '全部', name: '全部' },
      { id: '内科', name: '内科' },
      { id: '外科', name: '外科' },
      { id: '妇产科', name: '妇产科' },
      { id: '儿科', name: '儿科' },
      { id: '皮肤科', name: '皮肤科' },
      { id: '口腔科', name: '口腔科' },
      { id: '眼科', name: '眼科' },
      { id: '耳鼻喉科', name: '耳鼻喉' },
      { id: '精神科', name: '精神科' },
      { id: '中医科', name: '中医科' },
      { id: '急诊科', name: '急诊科' },
      { id: '康复科', name: '康复科' }
    ],  
    doctorList: [],      // 医生列表
    dateList: [],        // 日期列表
    // 时间段列表（固定列表）
    timeList: [
      { id: '08:00', time: '08:00' },
      { id: '08:30', time: '08:30' },
      { id: '09:00', time: '09:00' },
      { id: '09:30', time: '09:30' },
      { id: '10:00', time: '10:00' },
      { id: '10:30', time: '10:30' },
      { id: '11:00', time: '11:00' },
      { id: '11:30', time: '11:30' },
      { id: '14:00', time: '14:00' },
      { id: '14:30', time: '14:30' },
      { id: '15:00', time: '15:00' },
      { id: '15:30', time: '15:30' },
      { id: '16:00', time: '16:00' },
      { id: '16:30', time: '16:30' },
      { id: '17:00', time: '17:00' },
      { id: '17:30', time: '17:30' }
    ],
    
    selectedDepartment: '',  // 选中的科室ID
    selectedDoctor: '',      // 选中的医生ID
    selectedDoctorObj: null, // 选中的医生对象
    selectedDate: '',        // 选中的日期
    selectedTime: '',        // 选中的时间段
    
    loading: false,    // 是否正在加载数据
    submitLoading: false, // 提交时的加载状态
    
    // 病情描述
    description: '',
    showDescriptionModal: false // 控制病情描述弹窗显示
  },
  
  onLoad() {
    // 获取日期列表
    this.getDateList()
    
    // 如果科室列表有值，默认选中第一个
    if (this.data.departmentList.length > 0) {
      this.setData({
        selectedDepartment: this.data.departmentList[0].id
      })
      // 获取医生列表
      this.getDoctorList(this.data.departmentList[0].id)
    }
  },
  
  // 获取医生列表
  getDoctorList(department) {
    this.setData({ loading: true })
    
    const params = {}
    if (department && department !== '全部') {
      params.kezhen = department
    }
    
    console.log('获取医生列表参数:', params, '当前选择科室:', department)
    
    // 请求医生列表接口
    request.get('/student/doctor/getInfo', params, true)
      .then(res => {
        this.setData({ loading: false })
        
        if (res.code === 0 && res.data) {
          // 过滤和格式化医生数据
          const doctors = res.data.filter(doctor => 
            doctor.doctorname || (doctor.username && doctor.username !== 'admin')
          ).map(doctor => ({
            id: doctor.id,
            name: doctor.doctorname || doctor.username,
            avatar: doctor.image,
            department: doctor.kezhen || '未分类',
            hospital: doctor.hospital || '未知医院',
            title: doctor.kezhen ? `${doctor.kezhen} 医生` : '医生',
            fee: 5 // 默认挂号费
          }));
          
          this.setData({
            doctorList: doctors
          })
          
          // 默认选中第一个医生
          if (doctors.length > 0) {
            this.setData({
              selectedDoctor: doctors[0].id,
              selectedDoctorObj: doctors[0]
            })
          } else {
            this.setData({
              selectedDoctor: '',
              selectedDoctorObj: null
            })
          }
        } else {
          wx.showToast({
            title: res.message || '获取医生列表失败',
            icon: 'none'
          })
          this.setData({
            doctorList: [],
            selectedDoctor: '',
            selectedDoctorObj: null
          })
        }
      })
      .catch(err => {
        console.error('获取医生列表失败', err)
        this.setData({ 
          loading: false,
          doctorList: [],
          selectedDoctor: '',
          selectedDoctorObj: null
        })
        wx.showToast({
          title: '获取医生列表失败',
          icon: 'none'
        })
      })
  },
  
  // 获取日期列表
  getDateList() {
    // 获取未来7天的日期
    const dateList = []
    const now = new Date()
    
    for (let i = 0; i < 7; i++) {
      const date = new Date(now.getTime() + i * 24 * 60 * 60 * 1000)
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      const weekday = '周' + '日一二三四五六'.charAt(date.getDay())
      
      dateList.push({
        id: `${year}-${month}-${day}`,
        date: `${month}月${day}日`,
        weekday
      })
    }
    
    this.setData({
      dateList,
      selectedDate: dateList[0].id
    })
  },
  
  // 选择科室
  selectDepartment(e) {
    const departmentId = e.currentTarget.dataset.id
    
    if (departmentId === this.data.selectedDepartment) return
    
    this.setData({
      selectedDepartment: departmentId
    })
    
    // 获取医生列表
    this.getDoctorList(departmentId)
  },
  
  // 选择医生
  selectDoctor(e) {
    const doctorId = e.currentTarget.dataset.id
    
    if (doctorId === this.data.selectedDoctor) return
    
    const selectedDoctor = this.data.doctorList.find(item => item.id == doctorId)
    
    this.setData({
      selectedDoctor: doctorId,
      selectedDoctorObj: selectedDoctor || null
    })
  },
  
  // 选择日期
  selectDate(e) {
    const date = e.currentTarget.dataset.id
    
    if (date === this.data.selectedDate) return
    
    this.setData({
      selectedDate: date
    })
  },
  
  // 选择时间段
  selectTime(e) {
    const timeId = e.currentTarget.dataset.id
    
    this.setData({
      selectedTime: timeId
    })
  },
  
  // 提交挂号
  submitAppointment() {
    if (!this.data.selectedDepartment) {
      wx.showToast({
        title: '请选择科室',
        icon: 'none'
      })
      return
    }
    
    if (!this.data.selectedDoctor) {
      wx.showToast({
        title: '请选择医生',
        icon: 'none'
      })
      return
    }
    
    if (!this.data.selectedDate) {
      wx.showToast({
        title: '请选择日期',
        icon: 'none'
      })
      return
    }
    
    if (!this.data.selectedTime) {
      wx.showToast({
        title: '请选择时间段',
        icon: 'none'
      })
      return
    }
    
    // 判断是否已登录
    const token = wx.getStorageSync('token')
    if (!token) {
      wx.showModal({
        title: '提示',
        content: '请先登录后再挂号',
        confirmText: '去登录',
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/login/login'
            })
          }
        }
      })
      return
    }
    
    // 显示病情描述弹窗
    this.setData({ showDescriptionModal: true })
  },
  
  // 提交病情描述并挂号
  submitDescription() {
    this.setData({ submitLoading: true })
    
    // 构建挂号数据
    const deptName = this.data.selectedDepartment === '全部' ? 
                 (this.data.selectedDoctorObj?.department || '') : 
                 this.data.selectedDepartment
    
    // 格式化日期时间
    const appointmentDateTime = `${this.data.selectedDate} ${this.data.selectedTime}:00`
    
    const appointmentData = {
      appointmentTime: appointmentDateTime,
      doctorId: this.data.selectedDoctor,
      doctorName: this.data.selectedDoctorObj ? this.data.selectedDoctorObj.name : '',
      deptName: deptName,
      description: this.data.description,
      remark: '',
      status: 'PENDING'
    }
    
    console.log('提交挂号数据：', appointmentData)
    
    // 请求挂号接口
    request.post('/student/appointment/add', appointmentData, true)
      .then(res => {
        this.setData({ 
          submitLoading: false,
          showDescriptionModal: false
        })
        
        if (res.code === 0) {
          wx.showToast({
            title: '挂号成功',
            icon: 'success'
          })
          
          // 跳转到挂号记录页面
          setTimeout(() => {
            wx.navigateTo({
              url: '/pages/appointmentRecord/appointmentRecord'
            })
          }, 1500)
        } else {
          wx.showToast({
            title: res.message || '挂号失败',
            icon: 'none'
          })
        }
      })
      .catch(err => {
        console.error('挂号失败', err)
        this.setData({ 
          submitLoading: false,
          showDescriptionModal: false
        })
        
        wx.showToast({
          title: '挂号失败',
          icon: 'none'
        })
      })
  },
  
  // 取消病情描述
  cancelDescription() {
    this.setData({ showDescriptionModal: false })
  },
  
  // 输入病情描述
  inputDescription(e) {
    this.setData({ description: e.detail.value })
  },
}) 